/*
 * AVPacketQueue.cpp
 *
 *  Created on: 2015年6月23日
 *      Author: chuanjiang.zh@qq.com
 */

#include "AVPacketQueue.h"


AVPacketQueue::AVPacketQueue():
    m_packets(),
    m_cs()
{
}

AVPacketQueue::~AVPacketQueue()
{
    clear();
}

size_t AVPacketQueue::size()
{
    comn::AutoCritSec   lock(m_cs);
    return m_packets.size();
}

bool AVPacketQueue::empty()
{
    comn::AutoCritSec   lock(m_cs);
    return m_packets.empty();
}

size_t AVPacketQueue::push(AVPacketPtr& packet)
{
    size_t count = 0;
    {
        comn::AutoCritSec   lock(m_cs);
        m_packets.push_back(packet);

        count = m_packets.size();
    }

    return count;
}

AVPacketPtr AVPacketQueue::pop()
{
    AVPacketPtr packet;
    pop(packet);
    return packet;
}

bool AVPacketQueue::pop(AVPacketPtr& packet)
{
    bool found = false;
    comn::AutoCritSec   lock(m_cs);
    if (!m_packets.empty())
    {
        packet = m_packets.front();
        m_packets.pop_front();
        found = true;
    }
    return found;
}

void AVPacketQueue::clear()
{
    comn::AutoCritSec   lock(m_cs);
    while (!m_packets.empty())
    {
        AVPacketPtr packet = m_packets.front();
        m_packets.pop_front();
    }
}

int64_t AVPacketQueue::getDuration()
{
    int64_t duration = 0;
    comn::AutoCritSec   lock(m_cs);
    if (m_packets.size() > 1)
    {
        AVPacketPtr& frontPacket = m_packets.front();
        AVPacketPtr& backPacket = m_packets.back();
        duration = backPacket->dts - frontPacket->dts;
    }

    return duration;
}

bool AVPacketQueue::getHeadTime(int64_t& ts)
{
    comn::AutoCritSec   lock(m_cs);
    if (m_packets.empty())
    {
        return false;
    }

    ts = m_packets.front()->dts;
    return true;
}

int AVPacketQueue::getHeadFlag()
{
    comn::AutoCritSec   lock(m_cs);
    if (m_packets.empty())
    {
        return false;
    }

    return m_packets.front()->flags;
}

size_t AVPacketQueue::push(int index, uint8_t* data, int size, int64_t ts)
{
    AVPacketPtr pkt(new AVPacket(), AVPacketDeleter());
    av_init_packet(pkt.get());

    av_new_packet(pkt.get(), size);

    pkt->stream_index = index;
    pkt->dts = ts;

    memcpy(pkt->data, data, size);

    return push(pkt);
}

